/*
  Losu Copyright Notice
  --------------------
    Losu is an open source programming language project under the MIT license
  that can be used for both academic and commercial purposes. There are no
  fees, no royalties, and no GNU-like "copyright" restrictions. Losu qualifies
  as open source software. However, Losu is not public property, and founder
  'chen-chaochen' retains its copyright.

    Losu has been registered with the National Copyright Administration of the
  People's Republic of China, and adopts the MIT license as the copyright
  licensing contract under which the right holder conditionally licenses its
  reproduction, distribution, and modification rights to an unspecified public.

    If you use Losu, please follow the public MIT agreement or choose to enter
  into a dedicated license agreement with us.

  The MIT LICENSE is as follows
  --------------------
  Copyright  2020 - now  chen-chaochen

    Permission is hereby granted, free of charge, to any person obtaining a
  copy of this software and associated documentation files (the “Software”), to
  deal in the Software without restriction, including without limitation the
  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  sell copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
*/

/*
    This document is part of the Losu Community OSPP - 2024 subject results
  contributed by Dongqiao Huang @ NEUQ, following MIT LICENSE Contributed to
  the Losu Community.

  The MIT LICENSE is as follows
  --------------------
  Copyright 2024 Dongqiao Huang

    Permission is hereby granted, free of charge, to any person obtaining a
  copy of this software and associated documentation files (the “Software”), to
  deal in the Software without restriction, including without limitation the
  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  sell copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
 */

#include "hLexer.hh"

#include <cctype>
#include <cstring>
#include <iostream>

#include "hError.hh"

namespace LosuPreCompiler
{
namespace Lexer
{
/**
 * @fn hLexer::hLexer(std::string source)
 * @brief Constructor, initializes the lexer with the source code
 * @param source The source code to be lexed
 * @param filename The filename of the source code
 */
hLexer::hLexer (std::string source, std::string filename)
{
  this->source = std::stringstream (source);
  this->fName = filename;
  this->sSrc = "";
  this->sPos = 0;
  this->sLen = 0;
  this->sLine = 1;
  this->sEOZ = 0;
  this->tkType = -1; // -1 means no token has been read yet
  this->tkValue = "";
  this->synIdt.nowIdt = 0;
  this->synIdt.curIdt = 0;
  this->synIdt.size = 4;
  this->synIdt.idtNum = 0;
  this->nextToken ();
}

void
hLexer::nextToken ()
{
#define _return(tk, tkv)                                                      \
  {                                                                           \
    this->tkType = tk, this->tkValue = tkv;                                   \
    return;                                                                   \
  }

  try
    {
      while (1)
        {
          switch (this->CurChar ())
            {
            case '#':
              {
                while (this->CurChar () != '\n')
                  this->NextChar ();
                break;
              }
            case synTktype::TK_EOZ:
              {
                _return (synTktype::TK_EOZ, "EOZ");
                break;
              }
            case '\0':
            case ' ':
            case '\t':
              {
                this->NextChar ();
                break;
              }
            case synTktype::TK_END:
              {
                this->NextChar ();
                _return (synTktype::TK_END, "end");
                break;
              }
            case '\n':
              {
                this->NextChar ();
                this->sLine++;
                break;
              }
            case '"':
            case '\'':
              {
                _return (synTktype::TK_STRING,
                         this->ReadString (this->CurChar (), this->sLine));
                break;
              }
            default:
              {
                if (!std::isalpha (this->CurChar ()) && this->CurChar () != '_'
                    && this->CurChar () < 0x80)
                  {
                    int32_t c = this->CurChar ();
                    this->NextChar ();
                    // _return (synTktype::TK_NAME, c);
                    _return (c, c);
                  }
                std::string sName = this->ReadName ();

                // is keyword ?
                for (int32_t i = 0;
                     i < (int32_t)(sizeof (synTklist) / sizeof (synTklist[0]));
                     i++)
                  {
                    if (sName == std::string (synTklist[i].tkValue)
                        && synTklist[i].isKey)
                      {
                        if (synTklist[i].isKey > 1)
                          this->PushIndent ();
                        _return (synTklist[i].tkType,
                                 (std::string (synTklist[i].tkValue)));
                      }
                  }
                _return (synTktype::TK_NAME, sName);
                break;
              }
            }
        }
    }
  catch (std::string e)
    {
      LosuPreCompiler::Error::hError (
          std::string ("Syntax-Lexer"), this->fName, this->sLine,
          LosuPreCompiler::Error::hError::errCode::eCode_Lexer, e);
    }

#undef _return
}

std::int32_t
hLexer::getLine ()
{
  return this->sLine;
}

std::int32_t
hLexer::getTkType ()
{
  return this->tkType;
}

std::string
hLexer::getTkValue ()
{
  return this->tkValue;
}

std::int32_t
hLexer::CurChar ()
{
  // if exsist Idt ?
  if (this->synIdt.idtNum)
    return synTktype::TK_END;
  // if EOF ?
  if (this->sEOZ)
    return synTktype::TK_EOZ;
  // return sSrc[sPos];
  return this->sSrc[this->sPos];
}

void
hLexer::NextChar ()
{
  //  if exsist Idt ?
  if (synIdt.idtNum)
    {
      this->PopIndent ();
      this->synIdt.idtNum--;
      return;
    }

  // if EOF ?
  if (this->sEOZ)
    return;

  // Is at this line
  if (this->sPos < this->sLen)
    this->sPos++;
  else // get next line
    {
      if (std::getline (this->source, this->sSrc)) // read new line
        {
          this->sSrc += "\n";
          this->sLen = this->sSrc.length ();
          this->sPos = 0;
          this->synIdt.curIdt = 0; // reset idt

          // set idt
          while (1)
            {
              switch (this->sSrc[this->sPos])
                {
                case '\n':
                  {
                    break;
                  }
                case ' ':
                  {
                    this->synIdt.curIdt++;
                    this->sPos++;
                    continue;
                  }
                case '\t':
                  {
                    this->synIdt.curIdt += this->synIdt.size;
                    this->sPos++;
                    continue;
                  }
                default:
                  {
                    // if curIdt > nowIdt, throw error
                    if (this->synIdt.curIdt > this->synIdt.nowIdt)
                      throw (std::string (
                          "Invalid indentation, need less than '"
                          + std::to_string (this->synIdt.nowIdt) + "', but '"
                          + std::to_string (this->synIdt.curIdt) + "'."));

                    // if curIdt < nowIdt
                    if (this->synIdt.curIdt < this->synIdt.nowIdt)
                      {
                        // check if idt is Invalid, if curIdt % size != 0,
                        // throw error
                        if (this->synIdt.curIdt % this->synIdt.size)
                          throw (
                              "Invalid indentation, need Multiples of '"
                              + std::to_string (this->synIdt.size) + "', but '"
                              + std::to_string (this->synIdt.curIdt) + "'.");

                        // if valid,set Idt
                        this->synIdt.idtNum
                            = (this->synIdt.nowIdt - this->synIdt.curIdt)
                              / this->synIdt.size;
                      }
                    break;
                  }
                }
              break;
            }
          // reset sPos
          this->sPos = 0;
        }
      else // EOF
        {
          this->sSrc = "";
          this->sLen = 0;
          this->sPos = 0;
          this->sEOZ = 1;
          // if valid,set Idt
          this->synIdt.idtNum = this->synIdt.nowIdt / this->synIdt.size;
        }
    }
}

void
hLexer::PushIndent ()
{
  this->synIdt.nowIdt += this->synIdt.size;
}

void
hLexer::PopIndent ()
{
  this->synIdt.nowIdt -= this->synIdt.size;
}

std::string
hLexer::ReadName ()
{
  std::string sRet = "";
  while (1)
    {
      int32_t c = this->CurChar ();
      if (!(std::isalnum (c) || c == '_'))
        break;
      sRet += (char)c;
      this->NextChar ();
    }
  return sRet;
}

std::string
hLexer::ReadString (std::int32_t c, std::int32_t line)
{
  std::string sRet = "";
  this->NextChar ();
  while (this->CurChar () != c)
    {
      if (this->CurChar () == synTktype::TK_EOZ || this->CurChar () == '\n')
        throw (std::string ("String not closed (line '" + std::to_string (line)
                            + "')"));
      sRet += (char)this->CurChar ();
      this->NextChar ();
    }
  this->NextChar ();
  return sRet;
}

} // namespace Lexer
} // namespace LosuPreCompiler

#ifdef HLEXERCC_MAIN

#include <fstream>
int
main ()
{
  std::ifstream fin;
  fin.open ("test.els", std::ios::in);
  std::string s, t;
  while (std::getline (fin, t))
    s += t + "\n";
  fin.close ();
  LosuPreCompiler::Lexer::hLexer lex (s, "test.els");
  while (lex.getTkType () != lex.synTktype::TK_EOZ)
    {
      std::cout
          << lex.synTklist[lex.getTkType () - lex.synTktype::TK_EOZ].tkValue
          << "\t" << lex.getTkValue () << std::endl;
      lex.nextToken ();
    }

  /*
  LscLexer l1 (s);
  cout<< "| TK | TK_VAL |VAL|LINE|\n|---|---|---|---|\n";
  while (l1.current.type != TK_EOZ)
    {
      l1.next ();
      cout<< "|";
      cout << l1.current.type << "|"
           << lscTokenList[l1.current.type].tokenValue << "|"
           << l1.current.value << "|"
           << l1.linenum<<"|"<<endl;

    }
  */

  return 0;
}
#endif